<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getAddressList, getMedicalOrderPre, createMedicalOrder } from '@/services/order'
import { useRoute, useRouter } from 'vue-router'
import type { AddressItem, OrderPre } from '@/types/order';
import { error, success } from '@/utils/tools'
import OrderMedical from './components/OrderMedical.vue'
const route = useRoute()
const router = useRouter()

// 同意协议
const agree = ref(false)
// 药品信息
const orderPre = ref<OrderPre>()
// 收货地址列表信息(要默认显示的收货地址)
const address = ref<AddressItem>()
onMounted(async () => {
  // 获取药品预支付信息
  const { data } = await getMedicalOrderPre({ prescriptionId: route.query.id as string })
  orderPre.value = data
  // 获取收货地址数据
  const { data: allAddressResult } = await getAddressList()
  if (allAddressResult.length > 0) {
    // 看所有的收货地址中是否有isDefault为1的收货地址，如果有，就以该地址作为默认收货地址，否则就取所有地址的第1条作为默认地址来使用
    const defaultAddress = allAddressResult.find(item => item.isDefault === 1)
    if (defaultAddress) {
      address.value = defaultAddress
    } else {
      address.value = allAddressResult[0]
    }
  }
})

// 点击去支付按钮：1.创建药品订单；2.打开支付抽屉
// 药品订单
const orderId = ref('')
const loading = ref(false)
// 支付抽屉
const show = ref(false)
const submit = async () => {
  if (!agree.value) return error('请同意支付协议')
  if (!address.value?.id) return error('请选择收货地址')
  if (!orderPre.value?.id) return error('未找到处方')
  if (!orderId.value) {
    // 没有订单就先创建订单，然后再打开抽屉去支付
    try {
      loading.value = true
      const { data } = await createMedicalOrder({ id: orderPre.value.id, couponId: orderPre.value.couponId, addressId: address.value.id })
      // 更改orderId
      orderId.value = data.id
      success('创建订单成功')
      // 打开支付抽屉
      show.value = true
    } catch (err) {
      error('创建订单失败')
      router.push('/consult/order')
    } finally {
      loading.value = false
    }
  } else {
    // 打开抽屉去支付
    show.value = true
  }
}

// 支付地址
const payCallback = import.meta.env.VITE_API_URL

</script>

<template>
  <div class="order-pay-page" v-if="orderPre">
    <cp-nav-bar title="药品支付" />
    <div class="order-address" v-if="address">
      <p class="area">
        <van-icon name="location" />
        <span>{{ address.province + address.city + address.county }}</span>
      </p>
      <p class="detail">{{ address.addressDetail }}</p>
      <p>
        {{ address.receiver }}
        {{ address.mobile.replace(/^(\d{3})(?:\d{4})(\d{4})$/, '\$1****\$2') }}</p>
    </div>
    <order-medical :medicines="orderPre.medicines"></order-medical>
    <!-- <div class="order-medical">
      <div class="head">
        <h3>优医药房</h3>
        <small>优医质保 假一赔十</small>
      </div>
      <div class="item van-hairline--top" v-for="med in orderPre.medicines" :key="med.id">
        <img class="img" src="@/assets/ad.png" alt="" />
        <div class="info">
          <p class="name">
            <span>{{ med.name }}</span>
            <span>x{{ med.quantity }}</span>
          </p>
          <p class="size">
            <van-tag v-if="med.prescriptionFlag === 1">处方药</van-tag>
            <span>{{ med.specs }}</span>
          </p>
          <p class="price">￥{{ med.amount }}</p>
        </div>
        <div class="desc">{{ med.usageDosag }}</div>
      </div>
    </div> -->
    <div class="order-detail">
      <van-cell-group>
        <van-cell title="药品金额" :value="`￥${orderPre.payment}`" />
        <van-cell title="运费" :value="`￥${orderPre.expressFee}`" />
        <van-cell title="优惠券" :value="`-￥${orderPre.couponDeduction}`" />
        <van-cell title="实付款" :value="`￥${orderPre.actualPayment}`" class="price" />
      </van-cell-group>
    </div>
    <div class="order-tip">
      <p class="tip">
        由于药品的特殊性，如非错发、漏发药品的情况，药品一经发出
        不得退换，请核对药品信息无误后下单。
      </p>
      <van-checkbox v-model="agree">我已同意<a href="javascript:;">支付协议</a></van-checkbox>
    </div>
    <van-submit-bar :loading="loading" @click="submit" :price="orderPre.actualPayment * 100" button-text="立即支付"
      button-type="primary" text-align="left"></van-submit-bar>
    <!-- 支付方式的抽屉组件 -->
    <cp-pay-sheet :order-id="orderId" :actual-payment="orderPre.actualPayment" v-model:show="show"
      :pay-callback="payCallback"></cp-pay-sheet>
  </div>
</template>

<style lang="scss" scoped>
:deep(.van-nav-bar) {
  background-color: var(--cp-primary);

  .van-nav-bar__arrow,
  .van-nav-bar__title {
    color: #fff;
  }
}

:deep(.van-cell) {
  .van-cell__title {
    font-size: 16px;
  }

  .van-cell__value {
    font-size: 16px;
  }

  &.price {
    .van-cell__value {
      font-size: 18px;
      color: var(--cp-price);
    }
  }
}

:deep(.van-submit-bar) {
  box-shadow: 0 0 2px rgba(0, 0, 0, 0.1);

  .van-button {
    width: 200px;
  }
}

.order-pay-page {
  padding: 46px 0 65px;
}

.order-address {
  padding: 15px 15px 0 15px;
  background-color: #fff;
  font-size: 13px;

  .area {
    color: var(--cp-tag);
    margin-bottom: 5px;

    .van-icon-location {
      color: #ff7702;
      font-size: 14px;
    }
  }

  .detail {
    font-size: 17px;
    margin-bottom: 5px;
  }

  &::after {
    content: '';
    display: block;
    height: 12px;
    background-color: var(--cp-bg);
    margin: 0 -15px;
    margin-top: 15px;
  }
}

.order-tip {
  padding: 0 15px;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  margin-top: 10px;

  .tip {
    font-size: 12px;
    color: var(--cp-tag);
    width: 100%;

    &::before {
      content: '*';
      color: var(--cp-price);
      font-size: 14px;
    }

    margin-bottom: 30px;
  }

  .van-checkbox {
    a {
      color: var(--cp-primary);
    }
  }
}
</style>